<template>
  <div class="container">
    <div class="text-center upload-box">
      <div>
        <el-upload 
          ref="rebateUpload"
          class="upload-demo"
          drag
          :action="upload"
          name="excel"
          :limit="1"
          :before-upload="beforeUpload"
          :headers="headerUpload"
          :data="{type: 2}"
          :on-success="handleSuccess"
          :on-remove="handleRemove"
          :show-file-list="false"
          :on-error="handleError"
          v-show="isShowUpload">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">{{$t('page.drop')}}，<em>{{$t('page.click')}}</em></div>
        </el-upload>
        <div 
          class="reset-back"
          v-if="isShowStepOne">
          <div 
            class="link"
            @click="changLogData">
              {{$t('page.modData')}}
          </div>
          <span 
            class="link"
            @click="handleRemove"
              >{{$t('page.emptyData')}}
          </span>
        </div>
        <div class="upload-name-box">
          <div class="upload-name"
            v-show="isShowUploadtxt">
            {{uploadFile.name}}
            <el-button type='text'
              @click="handleRemove()">x</el-button>
          </div>
          <el-progress 
            :percentage="percentage"
            :color="customColor"
            v-show="isShowPer">
          </el-progress>
        </div>
      </div>
    </div>

    <div class="container-body"
         v-if="isShowStepOne">
      <template>
        <div class="title-space">
          <span>{{$t('page.ODvalue')}}：</span>
        </div>
        <div v-for="(listItem,listIndex) in tabelData" :key="listIndex">
          <div class="overflow">
            <table id="table-1">

              <tr v-for="(table,key,index) in listItem"
                  :key="index">
                  <!-- 表头 -->
                <td class="color-000">{{key!=='time'?key:$t('page.hole')}}</td>
                <!-- 标签 -->
                <td>
                  <span v-if="key !== 'time'">
                    {{markList[index-1]}}
                  </span>
                  <span class="color-000"
                        v-else>{{$t('page.mark')}}
                  </span>
                </td>
                <!-- 浓度 -->
                <td>
                  <span v-if="key!=='time'">
                    {{beforeLable[index-1]}}
                  </span>
                  <span class="color-000"
                        v-else>{{$t('page.label')}}({{unit}})
                  </span>
                </td>
                <!-- 数据 -->
                <td v-for="(iTable, index) in table" :key="index">
                  <span v-if="key!=='time'">{{iTable}}</span>
                  <span class="color-000"
                        v-else>{{iTable + 's'}}</span>
                </td>
              </tr>
            </table>
          </div>

          <div class="space"
               v-if="dissType === 'v1'">
            <div class="title-space">
              <span>{{$t('page.ODrate')}}（%）： </span>
            </div>

            <div class="overflow"
                 v-for="lightRateItem,lightRateIndex in lightRate" :key="lightRateIndex">
              <table id="table-1">
                <tr v-for="(table,key,index) in lightRateItem"
                    :key="index">
                  <td class="color-000">{{key!=='time'?key:$t('page.hole')}}</td>
                  <td>
                    <span v-if="key!=='time'">
                      {{beforeLable[index-1]}}{{unit}}
                    </span>
                    <span class="color-000"
                          v-else>
                      {{$t('page.parameter')}}
                    </span>
                  </td>
                  <td v-for="(iTable, index) in table" :key="index">
                    <span v-if="key!=='time'">{{iTable}}</span>
                    <span class="color-000"
                          v-else>{{iTable + 's'}}</span>
                  </td>
                </tr>
              </table>
            </div>
          </div>

          <div class="space text-center">
            <template v-for="(chart,index) in allLightRateCharts" >
              <div class="chart">
                <wave-chart :id="'LightRate1'+index"
                            :data='chart'></wave-chart>
              </div>
            </template>
          </div>

          <div class="space text-center">
            <template v-for="(chart,index) in allStepOneCharts">
              <template v-if="index === listIndex">
                <wave-chart 
                  v-show="graphicalList.includes('1')"
                  :key="index"
                  :id="'logStepOne1'+index"
                  :data='chart'
                  @shotImg="shotImg(graphicalList.includes('1'), $event)"
                ></wave-chart>
              </template>
            </template>
          </div>
          <linePointDiagram
            :value="originalData"
          ></linePointDiagram>
          <histogramVue 
            v-show="graphicalList.includes('2')"
            @shotImg="shotImg(graphicalList.includes('2'), $event)"
            :data="hisogramList"
            :resultValue="resultValue"
          />
        </div>

        <!-- 下载计算结果表 -->
        <div class="title-space">
          <span>{{$t('page.calResultes')}}：</span>
          <el-button 
            type="text"
            @click="downloadExl()"
            size="mini"
            >
              {{$t('page.export')}}
          </el-button>
        </div>

        <!-- <div class="title-space">
          <span>{{$t('page.molecular')}}（Da）：</span>
          {{mole}}
        </div> -->

        <div class="space"
             v-show="isShowStepTwo">

          <div v-if="dissType === 'v1'">
            <div class="overflow step-two">
              <table id="table-1">
                <template v-for="(stepTwoItem,TwoIndex) in stepTwoList">
                  <tr :key="TwoIndex"
                      v-for="(table,key,index) in stepTwoItem">
                    <td class="color-000" :key="index">
                      <span v-if="key!=='title'">{{key}}</span>
                      <span v-else>{{$t('page.hole')}}</span>
                    </td>
                    <td v-for="(iTable, index) in table" :key="index"  class="color-000">
                      <span  v-if="key ==='title'" v-html="iTable"></span>
                    </td>
                    <td v-for="(iTable, index) in table" :key="index">
                      <template v-if="key !=='title'">
                        <span :style="{color:iTable===extA?'#409eff':''}"
                              v-if="iTable===extA"> ({{$t('page.recommended')}}){{iTable}}</span>
                        <span v-else> {{iTable}}</span>
                      </template>
                    </td>
                  </tr>
                </template>
              </table>
            </div>

            <div class="img-list"
                 v-for="img,index in imgList"
                 :key="index"
                 style="width:60%;float:left;">
              <div class="img-item">
                <img :src="img"
                     alt="">
              </div>
            </div>

            <div style="width:40%;float:left;padding-left:50px;margin-top:25px;">
              <table id="table-2">
                <tr>
                  <td width="50%">
                    {{$t('page.formula')}}
                  </td>
                  <td>
                    y=x*Rmax/(x+KD)
                  </td>
                </tr>
                <tr>
                  <td width="50%">{{$t('page.parameter')}}</td>
                  <td>
                    <span class="data-item">Ka:{{parameter[1]}}</span>
                    <span class="data-item">Kd:{{parameter[2]}}</span>
                    <span class="data-item">KD:{{parameter[3]}}</span>
                  </td>
                </tr>

                <tr>
                  <td width="50%">{{$t('page.parameter')}}</td>
                  <td>
                    <span class="data-item">{{parameter[0]}}</span>
                  </td>
                </tr>
              </table>
            </div>
          </div>
          <div v-else>
            <div>
              <table id="table-1">

                <template v-for="resValue,resIndex in paramResult">
                  <tr>
                    <td v-for="v,k,i in resValue" :key="i">{{k}}</td>
                  </tr>
                  <tr>
                    <td v-for="v,k,i in resValue" :key="i">{{v}}</td>
                  </tr>
                </template>
              </table>
            </div>
          </div>

        </div>
      </template>
    </div>

    <!-- 弹窗 -->
    <el-dialog 
      :visible.sync="isShowInputLog"
      :close-on-click-modal="false"
      width="90%"
      top="5%"
      center>
      <div>
        <div class="space space-unit">
          <div class="space-title">{{$t('page.unit')}}：</div>
          <el-radio-group v-model="unit">
            <el-radio 
              :label="v"
              v-for="v,i in unitOption"
              :key="i">
            </el-radio>
          </el-radio-group>
        </div>
        <div class="space" style="margin: 20px 0;">
          <div class="space-title">{{ $t('page.module') }}：</div>
          <el-checkbox-group v-model="graphicalList">
            <el-checkbox label="1">{{ $t('page.ODvalue') + $t('page.curve') }}</el-checkbox>
            <el-checkbox label="2">{{ $t('page.endHistogram') }}</el-checkbox>
          </el-checkbox-group>
        </div>

        <!-- 本次修改药筛 -->
        <div class="space">
          <div class="label-title">
            <div class="space-title">{{$t('page.mark')}}：</div>
            <div class="space-title" style="margin-top: 36px;">{{$t('page.label')}} <br> ({{unit}})：</div>
          </div>
          <div style="overflow-x: auto;">
            <table id="table-1">
              <tr>
                <td 
                  v-for="(table,index) in waveName"
                  :key="index"
                  style="min-width: 100px;">
                  {{table}}
                </td>
              </tr>
              <tr>
                <td 
                  style="min-width: 100px;"
                  v-for="(table,index) in waveName"
                  :key="index">
                  <el-input type="text"
                    v-model="markList[index]"></el-input>
                </td>
              </tr>
              <tr>
                <td 
                  style="min-width: 100px;"
                  v-for="(table,index) in waveName"
                  :key="index">
                  <el-input type="Number"
                    v-model="beforeLable[index]"></el-input>
                </td>
              </tr>
            </table>
          </div>
        </div>

        <!-- 分子量 -->
        <!-- <div class="space">
          <div class="title-space">
            <div class="space-title">{{$t('page.molecular')}}（Da）：</div>
            <el-input 
              type="number"
              class="input"
              v-model="mole"
              style="width:500px;">
            </el-input>
          </div>
        </div> -->

        <!-- 是否归零 -->
        <div class="space" style="margin: 0 0 20px 0;">
          <div class="space-title">{{$t('page.zeroProcess')}}：</div>
          <el-radio v-model="zero" label='0'>{{$t('page.zero')}}</el-radio>
          <el-radio v-model="zero" label="1">{{$t('page.noZero')}}</el-radio>
        </div>
        <div class="space-btn">
          <el-button 
            type="primary"
            @click="handleCompute()"
            size="small"
            :loading="computeLoading"
            class="btn-submit-color">
              {{$t('page.submit')}}
          </el-button>
        </div>
      </div>
    </el-dialog>

  </div>
</template>
<script>
import waveChart from '@/components/WaveChart'
import { fetchaffinityYsstepB, fetchUploadExl } from '@/api/table'
import { setStore, getStore } from '@/utils/common'
import { getToken } from '@/utils/auth'
import store from '@/store'
import { COLORLIST } from '@/utils/variate'
import histogramVue from '../components/histogram.vue'
import linePointDiagram from '@/commonPage/linePointDiagram'
import { formatData } from '@/commonPage/linePointDiagram/formatData'

export default {
  data() {
    return {
      graphicalList: ['1', '2'],
      originalData: {},
      originalDataRate: [],
      lightRate: [],
      lightValue: [],
      stepTwoList: [],
      computeLoading: false, //显示计算loading
      computeAllowed: true, //防连点
      isShowInputLog: false, //是否显示公式
      isShowStepOne: false, //是否显示第一步表格
      isShowStepTwo: false, //是否显示第二步表格
      showScreenshotsImg: true, //页面上的曲线隐藏
      isShowUpload: true,
      isShowUploadtxt: false,
      uploadFile: {},
      // mole: '115207373',
      unit: 'μg/ml',
      unitOption: ['pg/ml', 'ng/ml', 'μg/ml', 'mg/ml'],
      isShowPer: false,
      percentage: 0,
      customColor: '#e6a23c',
      allLightRateCharts: [],
      allStepOneCharts: [],
      isRepeatSubmit: false,
      extA: '',
      imgList: '',
      unitTitle: [],
      parameter: [],
      waveName: [],
      beforeLable: [],   // 弹窗浓度表格
      markList: [],   // 弹窗标签表格
      baseStepOne: [],
      doDownload: false,
      paramResult: [],
      dissociation: [],
      dissType: '',
      zero: '0',   // 是否归零
      lang: getStore('spr-lang') || 'zh', // 语言类型
      resultValue: {},   // 计算之后的结果
      tooltipList: [],  // 用于echarts的tooltip数组
      hisogramList: {}, // 柱状图数据
      tabelData: [], 
    }
  },
  components: {
    waveChart,
    histogramVue,
    linePointDiagram,
  },
  methods: {
    goNext(route, type) {
      if (type === 1) {
        setStore('chartData', this.lightRate)
      }
      this.$router.push({ path: route })
    },
    changLogData() {
      this.isRepeatSubmit = true
      this.isShowInputLog = true
      this.doDownload = false
      // this.beforeLable = []
      // this.markList = []
    },
    beforeUpload(file) {
      this.uploadFile = file
      this.isShowPer = true
      this.isShowUpload = false
      this.isShowUploadtxt = true
      this.percentage += 60 + Math.floor(Math.random() * 10)
    },
    handleSuccess(file, filelist) {
      // file = {
      const next = 100 - this.percentage
      this.percentage += next
      setTimeout(() => {
        this.isShowPer = false
      }, 1000)
     
      if (file.status === 200) {
        this.waveName = file.data.hole
        this.isShowInputLog = true
        // this.beforeLable = []
        // this.waveName.forEach((item) => {
        //   this.beforeLable.push('')
        // })

        setStore('auuid', file.data.uuid)
      } else {
        if (file.status === 502) {
          this.$msgbox
            .confirm(this.$t('page.msgBoxLoginOut'), this.$t('page.loginOut'), {
              confirmButtonText: this.$t('page.loginAgin'),
              cancelButtonText: this.$t('page.cancel'),
              type: 'warning',
            })
            .then(() => {
              store.dispatch('FedLogOut').then(() => {
                location.reload()
              })
            })
        } else {
          this.$message.error(file.msg)
        }
      }
    },
    handleError(err) {
      this.$message.error(err)
    },
    async handleCompute() {
      if (this.computeAllowed) {
        this.showScreenshotsImg = true
        this.baseStepOne = []
        this.computeLoading = true
        try {
          let info = await fetchaffinityYsstepB({
            crpValue: this.beforeLable,
            uuid: getStore('auuid'),
            labValue: this.markList,
            // mole: this.mole,
            unit: this.unit,
            zero: Number(this.zero),
            isRepeatSubmit: this.isRepeatSubmit,
            imageSwitcher: this.graphicalList
          })
          if (info.status === 200) {
            this.paramResult = []
            this.originalData = {}
            this.tabelData = info.data.originalData
            this.originalData = {
              ...formatData(info.data.originalData[0]),
            }
  
            this.paramResult = info.data.paramResult
            this.dissociation = info.data.dissociation
            // echarts,legend数据
            this.resultValue = info.data.resultValue
            // 柱状图数据
            this.hisogramList = info.data.histogram
            this.dissType = info.data.extB
            if (this.isRepeatSubmit) {
              setStore('auuid', info.data.uuid)
            }
  
            //v1是旧表，v2是新表
            if (this.dissType === 'v1') {
              this.lightRate = info.data.lightRate
              this.stepTwoList = []
              this.stepTwoList = info.data.finalResult
  
              this.imgList = info.data.imgList
              this.extA = info.data.extA
              let loctionTitle = info.data.unitTitle
              loctionTitle.forEach((item) => {
                let title = []
                item.forEach((titleItem, index) => {
                  if (index === 4) {
                    const sub = `K<sub>a</sub>(10<sup>${titleItem}</sup>M<sup>-1</sup>S<sup>-1</sup>)`
                    title.push(sub)
                  } else if (index === 5) {
                    const sub = `K<sub>d</sub>(10<sup>${titleItem}</sup>S<sup>-1</sup>)`
                    title.push(sub)
                  } else if (index === 6) {
                    const sub = `K<sub>D</sub>(10<sup>${titleItem}</sup>S<sup>-1</sup>)`
                    title.push(sub)
                  } else {
                    title.push(titleItem)
                  }
                })
                const data = {}
                data.equa = title
                this.unitTitle.push(data)
              })
  
              this.stepTwoList.forEach((dataListItem) => {
                for (let i in dataListItem) {
                  if (dataListItem[i].indexOf(this.extA) === 0) {
                    this.parameter = dataListItem[i]
                  }
                }
              })
              const stepTwoTitle = { title: this.unitTitle[0].equa }
              this.stepTwoList.unshift(stepTwoTitle)
              this.stepTwoList.map((listItem) => {
                for (let i in listItem) {
                  listItem[i].splice(1, 3)
                }
              })
            }
  
  
            let _this = this
            _this.$nextTick(() => {
              setTimeout(() => {
                _this.imgUpLoad()
                _this.doDownload = true
              }, 3000)
            })
  
            this.isShowInputLog = false
            this.isShowStepOne = true
            this.isShowStepTwo = true
          } else {
            this.$message.error(info.msg)
          }
        } finally {
          this.computeLoading = false
        }
      }
    },
    async imgUpLoad() {
      await fetchUploadExl({
        crpValue: this.beforeLable,
        uuid: getStore('auuid'),
        // mole: this.mole,
        imgBase64: this.baseStepOne,
      })
    },
    handleRemove() {
      this.$refs['rebateUpload'].clearFiles() //清除文件
      //上传框
      this.isShowUpload = true
      this.isShowUploadtxt = false
      //可以计算
      this.computeAllowed = true
      this.computeLoading = false
      //上传进度条
      this.percentage = 0
      //显示进度
      this.isShowPer = false
      this.paramResult = []
      this.originalData = {}
      this.stepTwoList = []
      this.allStepOneCharts = []
      this.isShowStepOne = false
      this.isShowStepTwo = false
      this.isShowInputLog = false
      this.doDownload = false
      this.baseStepOne = []
      this.beforeLable = []   // 孔号数据
      this.markList = []   // 标签数据
      // this.mole = '115207373'
    },
    downloadExl() {
      if (this.isShowStepTwo && this.doDownload) {
        let lang = this.lang === 'zh' ? 'CN' : 'ENG'
        const href = `${
          process.env.BASE_URL
        }receive/download/excel/5/${lang}/${getStore('auuid')}`
        window.open(href, '_blank')
      } else {
        this.$message({
          type: 'error',
          message: this.$t('page.doDownload'),
        })
      }
    },
    opens() {
      setTimeout(() => {
        let triggerResize = new Event('resize')
        window.dispatchEvent(triggerResize)
      }, 0)
    },

    // legend返回title部分
    getLegendValue(val) {
      // 标签 > 浓度 > 孔号
      const { key = [], data1 = [], data2 = []} = this.resultValue
      const index = key.findIndex(item => item === val)
      let str = ''
      const result1 = data1.some(item => item)
      const result2 = data2.some(item => item)
      if(result1) {
        str = data1[index]
        this.tooltipList = data1
      } else if(result2) {
        str = data2[index]
        this.tooltipList = data2
      } else {
        str = val
        this.tooltipList = key
      }
      return str
    },


    shotImg(isPush = true, data) {
      if(!isPush) return
      this.baseStepOne.push(data)
    },
    // setImg(data) {
    //   this.baseStepOne.push(data)
    // }
  },
  computed: {
    upload: () => {
      return `${process.env.BASE_URL}affinityYs/affinity/upload/stepA`
    },
    headerUpload: () => {
      const data = {}
      data.TOKEN = getToken()
      if (localStorage.getItem('spr-lang') === 'en') {
        data.LANG = 'ENG' // 传语言
      }
      return data
    },
  },
}
</script>

<style lang="scss" scoped>
.space {
  display: flex;
  margin: 0;
  .space-title {
    width: 120px;
    display: flex;
    justify-content: flex-end;
    align-items: center
  }
  .space-title::before {
    content: '*';
    color: red;
    margin-right: 2px;
  }
  .label-title {
    display: flex;
    width: 120px;
    flex-direction: column;
    padding-top: 60px;
    align-items: flex-end;
    text-align: center;
  }
}
.space-unit {
  margin-bottom: 20px;
}
.space-btn {
  margin-left: 250px;
}
table {
  border-collapse: collapse;
  text-align: center;
  white-space: nowrap;
  margin-bottom: 20px;
}
.reset-back {
  display: flex;
  align-items: center;
  margin: 0 20px 20px;
  .link {
    cursor: pointer;
    color: #409eff;
    font-style: normal;
    margin-right: 20px;
  }
}
.img-list {
  width: 1000px;
  display: flex;
  flex-wrap: wrap;
}
.img-item {
  width: 500px;
}
// .overflow {
//     overflow: scroll;
// }

#table-2 {
  border-bottom-width: 1px;
  border-bottom-style: solid;
  border-bottom-color: #000;
}
#table-2 tr {
  border: 1px solid #000 !important;
}

#table-2 td:first-child {
  border-left: 1px solid #000;
}

/* Padding and font style */
#table-2 td,
#table-2 th {
  padding: 10px 15px;
  font-size: 12px;
  font-family: Verdana;
  border-right-width: 1px;
  border-right-style: solid;
}

.data-item {
  display: block;
}

@media screen and (min-width: 1000px) {
  .data-item {
    display: inline-block;
    margin-right: 20px;
  }
}
</style>